package com.wisdytech.linkdcs.log.service.impl;

import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.DateUtil;
import com.wisdytech.linkdcs.log.dao.ISysLogDao;
import com.wisdytech.linkdcs.log.dto.LogSearchDTO;
import com.wisdytech.linkdcs.log.model.SysLog;
import com.wisdytech.linkdcs.log.service.ISysLogService;
import com.wisdytech.linkdcs.system.model.SysResource;
import com.wisdytech.linkdcs.system.service.ISystemResourceService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


@Service("sysLogService")
@Transactional
public class SysLogServiceImpl extends BaseService<ISysLogDao, SysLog> implements ISysLogService {
	
	private static final Logger logger  = LoggerFactory.getLogger(SysLogServiceImpl.class);
    
    /**
     * 访问资源列表
     */
    private ConcurrentHashMap<String, SysResource> resourceMap= new ConcurrentHashMap<>();
    /**
     * 基础资源列表
     */
    private ConcurrentHashMap<String, SysResource> baseResourceMap= new ConcurrentHashMap<>();
    
    @Resource
    private ISysLogDao sysLogDao;
    
    @Resource
    private ISystemResourceService sysResourceService;
    
    
    
    @Override
	public String getModuldeName(String url) {
    	logger.info(">>>>>>>>>>>>>>>>>>the url is:[{}]<<<<<<<<<<<<<<<<<<<<",url);
    	SysResource resource =getResourceByUrl(url);
    	if(resource!=null) {
    		return resource.getResName();
    	}
		return null;
	}

	@Override
    public void add(SysLog log,String url) {
        SysResource  resource =getResource(url);
        //尚未匹配到资源
        if(resource==null){
            return;
        }
        log.setModule(resource.getResName());
        log.setRemark("访问"+resource.getResName()+"页面");
        
        sysLogDao.insert(log);
    }
    
    @Override
    public void addUserOperateLog(SysLog log,String url) {
        SysResource  resource =getResource(url);
        //尚未匹配到资源
        if(resource==null){
            return;
        }
        String str = resource.getResName();
        String moduleName = str.substring(0, str.length()-3);
        log.setModule(moduleName);
        log.setRemark(resource.getResName());
        sysLogDao.insert(log);
    }
    
    @Override
    public void addErrorLog(SysLog log, String url) {
        SysResource  resource =getBaseResource(url);
        //尚未匹配到资源
        if(resource==null){
            return;
        }
        String str = resource.getResName();
        String moduleName = "";
        if(StringUtils.isNotEmpty(str)) {
        	moduleName = str.substring(0, str.indexOf("-"));
        }
        log.setModule(moduleName);
        sysLogDao.insert(log);
    }
    
    /**
     * 
     * <p>Description: 根据请求url获取对应的资源,url为contextPath后面的字符串，不带参数</p>
     * @param url 请求url
     */
    private synchronized SysResource getResourceByUrl(String url){
    	
        if(StringUtils.isBlank(url)){
            return null;
        }
        //截取掉url最前面的/,和数据库匹配
        url = url.substring(1);
        if(resourceMap.size()==0){
            updateSystemResources();
        }
        
        return resourceMap.get(url);
    }
    
    /**
     * 
     * <p>Description: 根据请求url获取对应的资源</p>
     * @param url 请求url
     */
    private synchronized SysResource getResource(String url){
        if(StringUtils.isBlank(url)){
            return null;
        }
        
        if(resourceMap.size()==0){
            updateSystemResources();
        }
        
        /*Set<String> keys= resourceMap.keySet();
        for(String key : keys){
            //包含资源url 获取对应的资源
            if(url.contains(key)){
                return resourceMap.get(key);
            }
        }
        //未找到对应的资源，返回
        return null;*/
        return resourceMap.get(url);
        
        
    }
    
    /**
     * 
     * <p>Description: 根据url获取基础的资源列表</p>
     * @param url 请求url
     * @return
     */
    private synchronized SysResource getBaseResource(String url){
        if(StringUtils.isBlank(url)){
            return null;
        }
        
        if(baseResourceMap.size()==0){
            updateSystemResources();
        }
        
        /*Set<String> keys= baseResourceMap.keySet();
        for(String key : keys){
            //包含资源url 获取对应的资源
            if(url.contains(key)){
                return baseResourceMap.get(key);
            }
        }
        //未找到对应的资源，返回
        return null;*/
        return baseResourceMap.get(url);
        
    }
    
    /**
     * 
     * <p>Description:更新资源列表</p>
     */
    private synchronized void updateSystemResources(){
        List<SysResource> resources =
                sysResourceService.listAllPageResource();
        resourceMap =new ConcurrentHashMap<>();
        baseResourceMap =new ConcurrentHashMap<>();
        for(SysResource resource : resources){
            //根据url是否为空保存访问资源
            if(StringUtils.isNotBlank(resource.getUri())){
                resourceMap.put(resource.getUri(), resource);
            }
            //根据baseUrl确认访问哪个模块
            if(StringUtils.isNotBlank(resource.getUri())){
                baseResourceMap.put(resource.getUri(), resource);
            }
            
            
        }
        
        
        
    }

    @Override
    public PageInfo<SysLog> listSysUsers(LogSearchDTO search, Filter filter) {
        
        
        
        //开始时间 //结束时间
        if(StringUtils.isBlank(search.getStartTime())
                && StringUtils.isBlank(search.getEndTime())){

            Date startTime=null;
            Date endTime=null;
            //时间不正确，获取当前时间
            endTime=new Date();
            //30天前的日期
            startTime =DateUtil.getDayTime(endTime, -30);

            search.setStartTime(DateUtil.getDefaultDateStr(startTime));
            search.setEndTime(DateUtil.getDefaultDateStr(endTime));
   
        }
        
        
        List<SysLog> lists =  super.beforeList(ISysLogDao.class, filter).selectLogBySearch(search);
        PageInfo<SysLog> logPage=new PageInfo<>(lists);
        return logPage;
    }

    @Override
    public PageInfo<SysLog> listLogs(Map<String, Object> queryMap, Filter filter) {
        List<SysLog> lists =  super.beforeList(ISysLogDao.class, filter).selectLogByQueryMap(queryMap);
        PageInfo<SysLog> logPage=new PageInfo<>(lists);
        return logPage;
    }


    @Override
    public String getErrorLogDetail(String pkId) {
        String detail = sysLogDao.selectErrorLogDetail(pkId);
        return detail;
    }
}
